<script lang="ts" setup>
import {game, GameStage} from "@/Game/Game";
import {PlayerArea as GamePlayerArea} from "@/Game/PlayerArea";
import {onMounted} from "vue";
import {useTheme} from "vuetify";
import {useAppStore} from "@/stores/app";

const theme = useTheme();
const appStore = useAppStore();
const forceShowContinueButton = ref(false);
const playerTab = ref(0);
const playerCount = ref(4);

const superNarrowScreen = ref(false);

onMounted(() => {
    globalThis.game = game;
    superNarrowScreen.value = globalThis.innerWidth < 700;
});

function continueGame() {
    if (game.gameStage == GameStage.End) {
        game.continueAfterEnd();
    }
    else {
        game.showNewGameDialog = false;
    }
}

watchEffect(async () => {
    playerTab.value = game.activePlayerIndex;
});

function togglePlayBy(playerArea: GamePlayerArea) {
    if (playerArea.robot) {
        playerArea.playByHuman = !playerArea.playByHuman;
    }
}

function toggleTheme() {
    const isDark = theme.global.current.value.dark;
    if (isDark) {
        document.documentElement.classList.remove("dark");
    }
    else {
        document.documentElement.classList.add("dark");
    }
    theme.global.name.value = isDark ? "light" : "dark";
}

const enableTransitions = () => "startViewTransition" in document && globalThis.matchMedia("(prefers-reduced-motion: no-preference)").matches;

async function toggleThemeWithEffect({
    clientX: x,
    clientY: y
}: MouseEvent) {
    if (!enableTransitions()) {
        toggleTheme();
        return;
    }

    const isDark = theme.global.current.value.dark;

    const clipPath = [`circle(0px at ${x}px ${y}px)`, `circle(${Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))}px at ${x}px ${y}px)`];

    await document.startViewTransition(async () => {
        toggleTheme();
        await nextTick();
    }).ready;

    document.documentElement.animate({clipPath: isDark ? clipPath.reverse() : clipPath}, {
        duration: 500,
        easing: "ease-in",
        pseudoElement: `::view-transition-${isDark ? "old" : "new"}(root)`
    });
}

function openUrl(url: string) {
    globalThis.open(url);
}
</script>

<template>
    <div style="display: flex; align-items: stretch; gap: 0.5rem; flex-wrap: wrap; height: 100vh; overflow: auto;">
        <CommonArea :commonArea="game.commonArea"/>
        <v-divider vertical/>
        <v-sheet :style="{minWidth: appStore.wideScreen ? '49.5rem' : '40.7rem'}" style="height: 100%; overflow: hidden; position: relative;">
            <v-chip v-if="game.roundCount >= 0" style="position: absolute; top: 0.75rem; left: 1rem;">第 {{Math.ceil(game.roundCount / game.playerAreas.length) + 1}} 回合
            </v-chip>
            <v-tabs v-model="playerTab" align-tabs="center" color="primary">
                <v-tab v-for="(item, index) in game.playerAreas" :key="index" :value="index">
                    <span v-if="index == game.activePlayerIndex" style="color: #d81b60;">• </span><span>玩家 {{index + 1}}</span> <span @click="(e)=>{e.stopPropagation(); togglePlayBy(item);}">
                        <template v-if="item.playByHuman">🧑</template>
                        <template v-else>🤖</template>
                    </span>
                </v-tab>
            </v-tabs>
            <v-tabs-window v-model="playerTab" style="height: 100%; overflow: hidden;">
                <v-tabs-window-item v-for="(item, index) in game.playerAreas" :key="index" :value="index" style="height: calc(100% - 3rem);">
                    <PlayerArea :playerArea="item"/>
                </v-tabs-window-item>
            </v-tabs-window>
        </v-sheet>
    </div>
    <v-fab :style="{top: appStore.wideScreen ? '3rem' : undefined, bottom: appStore.wideScreen ? undefined : '3rem'}" icon="mdi-theme-light-dark" style="position: fixed; right: 5rem;" @click="toggleThemeWithEffect"/>
    <v-fab :style="{top: appStore.wideScreen ? '7rem' : undefined, bottom: appStore.wideScreen ? undefined : '7rem'}" icon="mdi-refresh" style="position: fixed; right: 5rem;" @click="game.showNewGameDialog = true; forceShowContinueButton = true;"/>
    <v-fab :style="{top: appStore.wideScreen ? '11rem' : undefined, bottom: appStore.wideScreen ? undefined : '11rem'}" icon="mdi-code-tags" style="position: fixed; right: 5rem;" target="_blank" @click="openUrl('https://atomgit.com/xiaofengdizhu/splendor-in-song');"/>
    <v-snackbar v-model="game.showToast" :timeout="game.toastDuration" rounded="t-lg b-0" style="margin-bottom: 0;">
        <div style="text-align: center;">{{game.toastText}}</div>
    </v-snackbar>
    <v-dialog v-model="game.showConfirmDialog" width="auto">
        <v-card :text="game.confirmDialogText" :title="game.confirmDialogTitle" max-width="400">
            <template v-slot:actions>
                <v-btn color="primary" text="确认" variant="text" @click="game.confirmDialogCallback()"></v-btn>
                <v-btn text="取消" variant="text" @click="game.showConfirmDialog = false;"></v-btn>
            </template>
        </v-card>
    </v-dialog>
    <v-dialog v-model="game.showNewGameDialog" persistent width="auto">
        <v-card :title="game.lastWinnerIndex > -1 ? `玩家 ${game.lastWinnerIndex + 1} 胜利！` : '开始新游戏'" max-width="400">
            <v-card-text>
                <div>游戏目标：建造 8 家店铺并且持有金钱超过 50 两。</div>
                <div style="margin: 2rem 0;">
                    <v-select v-model="playerCount" :items="[1,2,3,4]" label="玩家数量" style="margin: 0 auto; width: 10rem;" variant="outlined"></v-select>
                </div>
                <div v-if="superNarrowScreen">屏幕过窄，建议横屏游玩</div>
            </v-card-text>
            <v-card-actions>
                <v-btn :text="game.lastWinnerIndex > -1 ? '重新开始' : '确认'" color="primary" variant="text" @click="game.startNewGame(playerCount)"></v-btn>
                <v-btn v-if="forceShowContinueButton || game.lastWinnerIndex > -1" :text="game.lastWinnerIndex > -1 ? '继续' : '取消'" variant="text" @click="continueGame()"></v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>